package com.xjh.uitl;

import com.xjh.Student;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StudentDao {
    JDBCUtil jdbcUtil = new JDBCUtil();

    public StudentDao() throws SQLException, ClassNotFoundException {
    }

    public List<Student> getStudent() throws SQLException, ClassNotFoundException {
        Connection conn = jdbcUtil.getConn();
        String sql = "select * from student";

        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet resultSet = ps.executeQuery();
        List<Student> list = new ArrayList<>();
        while (resultSet.next()) {
            String name = resultSet.getString("name");
            Integer age = resultSet.getInt("age");
            String address = resultSet.getString("address");
            String password = resultSet.getString("password");
            Student s = new Student(name, age, address,password);
            list.add(s);


        }
        return list;


    }


    public int insert(Student stu) throws SQLException, ClassNotFoundException {
        Connection conn = jdbcUtil.getConn();
        String sql="insert into student values(?,?,?,?)";

        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,stu.getName());
            ps.setInt(2,stu.getAge());
            ps.setString(3,stu.getAddress());
            ps.setString(4,stu.getPassword());

            int i = ps.executeUpdate();
            return i;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }

    public int deleteByName(String name ,String password) throws SQLException, ClassNotFoundException {
        Connection conn = jdbcUtil.getConn();
        String sql="delete from student where name=? and password=?";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setString(2,password);
            int i = ps.executeUpdate();
            return i;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }


    public int update(Student stu) throws SQLException, ClassNotFoundException {
        Connection conn = jdbcUtil.getConn();
        String sql="update student set age=?,address=? where password=? and name=?";
        PreparedStatement ps = conn.prepareStatement(sql);

        ps.setInt(1,stu.getAge());
        ps.setString(2,stu.getAddress());
        ps.setString(3,stu.getPassword());
        ps.setString(4,stu.getName());

        int i = ps.executeUpdate();

        return i;


    }

}
